package com.bwc.codevideo.speak

import android.os.Handler
import android.os.Looper
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.bwc.codevideo.R

class SpeakAdapter(private val items: MutableList<String>):RecyclerView.Adapter<SpeakAdapter.SpeakViewHolder>() {


    class SpeakViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val textView: TextView = itemView.findViewById(R.id.tv_speak_output)
        val image: ImageView = itemView.findViewById(R.id.im_speak_icon)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SpeakViewHolder {
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.item_speak, parent, false)
        return SpeakViewHolder(view)
    }

    override fun getItemCount(): Int = items.size

    override fun onBindViewHolder(holder: SpeakViewHolder, position: Int) {
        holder.textView.text = items[position]
        if (position % 2 == 1) {
            holder.image.background = holder.itemView.context.getDrawable(R.drawable.person)
        } else {
            holder.image.background = holder.itemView.context.getDrawable(R.drawable.boat)
        }
    }


    fun addItem(item: String) {
        items.add(item)
        notifyItemInserted(items.size - 1)
    }



    private var newStrings = ""

    fun addItems(currentTimes : Long,lastTime : Long,newString: String) {
        // 如果已经有条目，就合并新的消息
        val newCreate = 3000

        if (items.isNotEmpty()) {
            if (currentTimes - lastTime >newCreate){
                items.add("")
                newStrings = ""
            }
            newStrings += newString
            updateItem(items.size -1 ,newStrings)
            notifyItemChanged(items.size -1 )
        }else {
            // 如果没有任何数据，直接插入新的条目
            items.add(newString)
            notifyItemInserted(items.size - 1)
        }

    }

    fun removeItem(position: Int) {
        if (position in items.indices) {
            items.removeAt(position)
            notifyItemRemoved(position)
        }
    }


    fun updateItem(position: Int, newItem: String) {
        if (position in items.indices) {
            items[position] = newItem
            notifyItemChanged(position)
        }
    }

    fun clearItems() {
        val size = items.size
        items.clear()
        notifyItemRangeRemoved(0, size)
    }

    fun scrollToBottom(recyclerView: RecyclerView) {
        recyclerView.scrollToPosition(items.size - 1)
    }

    fun getUserInput(): String? {
        return items
            .filterIndexed { index, _ -> index % 2 == 1 }
            .joinToString(",")
    }
}
